package com.mac.bluetoothbt.feature;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.jingchen.timerpicker.PickerView;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import static com.mac.bluetoothbt.feature.Main2Activity.DEVICESTATE;

/**
 * @author wyh
 */
public class Setting1Activity extends AppCompatActivity {

    DeviceEntity deviceEntity;
    DeviceEntity originDeviceEntity;
    List<Sensor> sensors = null;
    PickerView picker1, picker2, picker3;
    EditText lowLimitEditText, highLimitEditText;
    EditText fullPointCompensation, zeroPointCompensation;
    private int settingIndex = 0;
    private BroadcastReceiver receiver;
    private boolean isWriting = false;

    @Override
    protected void onCreate(Bundle savedInstance) {
        super.onCreate(savedInstance);
        setContentView(R.layout.setting1);

        Intent intent = getIntent();
        if (intent.hasExtra(DEVICESTATE)) {
            deviceEntity = (DeviceEntity) intent.getSerializableExtra(DEVICESTATE);
            originDeviceEntity = ((App) getApplication()).getDeviceEntity();
            if (originDeviceEntity == null) {
                originDeviceEntity = new DeviceEntity(deviceEntity);
            }
            sensors = deviceEntity.getSensors();
        }

        IntentFilter filter = new IntentFilter();
        filter.addAction(Actions.ACTION_WRITE_END);
        filter.addAction(Actions.ACTION_WRITE_SUCCESS);
        filter.addAction(Actions.ACTION_WRITE_FAIL);
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (Actions.ACTION_WRITE_END.equals(intent.getAction())) {
                    if (isWriting) {
                        startActivity(new Intent()
                                .setClass(getApplication(), Main2Activity.class)
                                .putExtra(DEVICESTATE, deviceEntity));
                        isWriting = false;
                    }
                } else if (Actions.ACTION_WRITE_SUCCESS.equals(intent.getAction())) {
                    Toast.makeText(getApplication()
                            , "设置成功", Toast.LENGTH_LONG)
                            .show();
                    startActivity(new Intent()
                            .setClass(Setting1Activity.this, Main2Activity.class)
                            .putExtra(DEVICESTATE, deviceEntity));
                } else if (Actions.ACTION_WRITE_FAIL.equals(intent.getAction())) {
                    Toast.makeText(getApplication()
                            , "设置失败", Toast.LENGTH_LONG)
                            .show();
                    startActivity(new Intent()
                            .setClass(Setting1Activity.this, Main2Activity.class)
                            .putExtra(DEVICESTATE, deviceEntity));
                }
            }
        };
        registerReceiver(receiver, filter);

        //暂存浮点字面量
        initLiteralSave();

        picker1Setting();
        picker2Setting();
        picker3Setting();
        lowLimitSetting(0);
        highLimitSetting(0);
        zeroPointSetting(0);
        fullPointSetting(0);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }


    private void picker1Setting() {
        picker1 = findViewById(R.id.picker1);
        List<String> channelnumdata = new ArrayList<>();
        for (int i = 1; i <= deviceEntity.getChannelAmount(); i++) {
            channelnumdata.add(Integer.toString(i));
        }
        picker1.setData(channelnumdata);
        picker1.setSelected(0);
        picker1.invalidate();
        picker1.setOnSelectListener(new PickerView.onSelectListener() {
            @Override
            public void onSelect(String text) {
                changeToSensor(Integer.parseInt(text) - 1);
            }
        });
    }

    private void picker2Setting() {
        picker2 = findViewById(R.id.picker2);
        picker2.setData(FrameUtil.getAllGas());
        picker2.setSelected(sensors.get(0).getGasIndex());
        picker2.invalidate();
        picker2.setOnSelectListener(new PickerView.onSelectListener() {
            @Override
            public void onSelect(String text) {
                deviceEntity.setGasClass(settingIndex, FrameUtil.getGasIndex(text));
            }
        });
    }

    private void picker3Setting() {
        picker3 = findViewById(R.id.picker3);
        picker3.setData(FrameUtil.getAllRanges());
        int measureIndex = sensors.get(settingIndex).getMeasureRangeIndex();
        if (measureIndex >= FrameUtil.getAllRanges().size()) {
            measureIndex = 0;
        }
        picker3.setSelected(measureIndex);
        picker3.invalidate();
        picker3.setOnSelectListener(new PickerView.onSelectListener() {
            @Override
            public void onSelect(String text) {
                final int idx = FrameUtil.getRangeIndex(text);
                deviceEntity.setMeasureRangeIndex(settingIndex, idx);
                literalSaves[settingIndex][PRESSURE_MIN_STR] = getFormatedFloatStr(FrameUtil.LOW_LIMITES[idx]);
                lowLimitEditText.setText(literalSaves[settingIndex][PRESSURE_MIN_STR]);
                literalSaves[settingIndex][PRESSURE_MAX_STR] = getFormatedFloatStr(FrameUtil.HIGH_LIMITS[idx]);
                highLimitEditText.setText(literalSaves[settingIndex][PRESSURE_MAX_STR]);
            }
        });
    }

    private void lowLimitSetting(int index) {
        lowLimitEditText = findViewById(R.id.editText3);
        lowLimitEditText.setText(literalSaves[index][PRESSURE_MIN_STR]);
    }

    private void highLimitSetting(int index) {
        highLimitEditText = findViewById(R.id.editText2);
        highLimitEditText.setText(literalSaves[index][PRESSURE_MAX_STR]);
    }

    private void zeroPointSetting(int index) {
        zeroPointCompensation = findViewById(R.id.editTextZeroCompensation);
        zeroPointCompensation.setText(literalSaves[index][ZERO_POINT_STR]);
    }

    private String getZeroPointStr() {
        return getFormatedFloatStr(deviceEntity.getZeroPointCompensation());
    }

    private void fullPointSetting(int index) {
        fullPointCompensation = findViewById(R.id.editTextFullCompensation);
        fullPointCompensation.setText(literalSaves[index][FULL_POINT_STR]);
    }

    private String getFullPointStr() {
        return getFormatedFloatStr(deviceEntity.getFullPointCompensation());
    }

    @Override
    protected void onResume() {
        super.onResume();
        Intent intent = getIntent();
        if (intent.hasExtra(DEVICESTATE)) {
            deviceEntity = (DeviceEntity) intent.getSerializableExtra(DEVICESTATE);
            sensors = deviceEntity.getSensors();
        }
        picker1.setSelected(0);
        picker1.invalidate();
        settingIndex = 0;
        picker2.setSelected(sensors.get(0).getGasIndex());
        picker2.invalidate();
        highLimitSetting(0);
        lowLimitSetting(0);
    }

    void changeToSensor(int settingIndex) {
        updateTextviewData();
        this.settingIndex = settingIndex;
        sensors = deviceEntity.getSensors();
        picker2.setData(FrameUtil.getAllGas());
        picker2.setSelected(sensors.get(settingIndex).getGasIndex());
        picker2.invalidate();
        picker3.setData(FrameUtil.getAllRanges());
        int measureIndex = sensors.get(settingIndex).getMeasureRangeIndex();
        if (measureIndex >= FrameUtil.getAllRanges().size()) {
            measureIndex = 0;
        }
        picker3.setSelected(measureIndex);
        picker3.invalidate();
        highLimitSetting(settingIndex);
        lowLimitSetting(settingIndex);
    }

    private final String[][] literalSaves = new String[6][4];
    private final String[][] literalSavesOrigin = new String[6][4];
    private static int PRESSURE_MAX_STR = 0, PRESSURE_MIN_STR = 1, ZERO_POINT_STR = 2, FULL_POINT_STR = 3;

    private void initLiteralSave() {
        for (int i = 0; i < 6; i++) {
            literalSaves[i][PRESSURE_MAX_STR] = getPressureMaxStr(i);
            literalSaves[i][PRESSURE_MIN_STR] = getPressureMinStr(i);
            literalSaves[i][ZERO_POINT_STR] = getZeroPointStr();
            literalSaves[i][FULL_POINT_STR] = getFullPointStr();
            literalSavesOrigin[i][PRESSURE_MAX_STR] = getPressureMaxStr(i);
            literalSavesOrigin[i][PRESSURE_MIN_STR] = getPressureMinStr(i);
            literalSavesOrigin[i][ZERO_POINT_STR] = getZeroPointStr();
            literalSavesOrigin[i][FULL_POINT_STR] = getFullPointStr();
        }
    }

    private String getPressureMaxStr(int settingIndex) {
        return getFormatedFloatStr(sensors.get(settingIndex).getPressureMax());
    }

    private String getPressureMinStr(int settingIndex) {
        return getFormatedFloatStr(sensors.get(settingIndex).getPressureMin());
    }

    public void settingNextPageOnClicked(View view) {
        updateTextviewData();
        startActivity(new Intent().setClass(this
                , Setting2Activity.class)
                .putExtra(DEVICESTATE, deviceEntity));
    }

    public String getFormatedFloatStr(float fv) {
        BigDecimal pressurMax = new BigDecimal(((Number)fv).toString());
        return pressurMax
                .setScale(2, BigDecimal.ROUND_DOWN)
                .toPlainString();
    }

    public void settingCancelOnClicked(View view) {
        startActivity(new Intent()
                .setClass(this, Main2Activity.class)
                .putExtra(DEVICESTATE, deviceEntity));
    }

    private void updateTextviewData() {
        //更新TextView中的数据，在确认和下一页和通道切换中调用
        EditText upLimitEditText = findViewById(R.id.editText2);
        EditText loLimitEditText = findViewById(R.id.editText3);
        EditText zeLimitEditText = findViewById(R.id.editTextZeroCompensation);
        EditText maLimitEditText = findViewById(R.id.editTextFullCompensation);
        try {
            float upLimit = Float.parseFloat(upLimitEditText.getText().toString());
            float loLimit = Float.parseFloat(loLimitEditText.getText().toString());
            float zePoint = Float.parseFloat(zeLimitEditText.getText().toString());
            float maLimit = Float.parseFloat(maLimitEditText.getText().toString());

            float upLimitOrigin = Float.parseFloat(literalSavesOrigin[settingIndex][PRESSURE_MAX_STR]);
            float loLimitOrigin = Float.parseFloat(literalSavesOrigin[settingIndex][PRESSURE_MIN_STR]);
            float zePointOrigin = Float.parseFloat(literalSavesOrigin[0][ZERO_POINT_STR]);
            float maLimitOrigin = Float.parseFloat(literalSavesOrigin[0][FULL_POINT_STR]);

            literalSaves[settingIndex][PRESSURE_MAX_STR] = upLimitEditText.getText().toString();
            literalSaves[settingIndex][PRESSURE_MIN_STR] = lowLimitEditText.getText().toString();
            literalSaves[0][ZERO_POINT_STR] = zeLimitEditText.getText().toString();
            literalSaves[0][FULL_POINT_STR] = maLimitEditText.getText().toString();
            final float diff = 0.01f;
            if (Math.abs(upLimit - upLimitOrigin) > diff) {
                deviceEntity.setMax(settingIndex, upLimit);
            }
            if (Math.abs(loLimit - loLimitOrigin) > diff) {
                deviceEntity.setMin(settingIndex, loLimit);
            }
            if (Math.abs(zePoint - zePointOrigin) > diff) {
                deviceEntity.setZeroPointCompensation(zePoint);
            }
            if (Math.abs(maLimit - maLimitOrigin) > diff) {
                deviceEntity.setFullPointCompensation(maLimit);
            }
        } catch (NumberFormatException e) {
            Toast.makeText(this, "输入值错误", Toast.LENGTH_LONG).show();
        }
    }

    public void settingConfirmOnClicked(View view) {
        updateTextviewData();
        WriteRegistersGenerator writeRegistersGenerator =
                new WriteRegistersGenerator(deviceEntity, originDeviceEntity);
        List<byte[]> writeRegisterFrameList = writeRegistersGenerator.getWriteRegisterFrames();

        sendBroadcast(new Intent(Actions.ACTION_SETTING).putExtra("settingdata", (Serializable) writeRegisterFrameList));
        playgif();
    }

    void playgif() {
        setContentView(View.inflate(this, R.layout.loadinggif, null));
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}
